leetcode/lintcode刷题系-Expression Expand

Expression Expand

Given an expression s includes numbers, letters and brackets. Number represents the number of repetitions inside the brackets(can be a string or another expression).Please expand expression to be a string.

Examples = abc3[a] return abcaaa
s = 3[abc] return abcabcabc
s = 4[ac]dy, return acacacacdy
s = 3[2[ad]3[pf]]xyz, return adadpfpfpfadadpfpfpfadadpfpfpfxyz

语法整理:

Integer.valueOf(int i)//returns an integer object holds the value of specified primitives, 返回一个保存原指定数的整数对象。

Integer.valueOf(String s)//This returns an Integer object holding the value of the specified string representation.返回一个保存原指定string的整数对象。

Stack stack = new Stack(); //a templetate of stack, use explicit conversion to convert to some class.

Character.isDigit(c) //check if a character is ‘0’-‘9’

Integer count = (Integer)stack.pop();

instanceof //check type of the object

public class Solution {
/**
 * @param s  an expression includes numbers, letters and brackets
 * @return a string
 */
public String expressionExpand(String s) {
    // Write your code here
    Stack<Object> stack = new Stack<Object>();
    int number = 0;
    for(char c: s.toCharArray()){
        if(Character.isDigit(c)){
            number = number * 10 + (c-'0');
        }else if(c == '['){
            stack.push(Integer.valueOf(number));
            number = 0;
        }else if(c == ']'){
            String temp = popStack(stack);
            Integer count = (Integer)stack.pop();
            while(count > 0){
                stack.push(temp);
                count--;
            }
        }else{
            stack.push(String.valueOf(c));
        }
    }
    return popStack(stack);
}

String popStack(Stack<Object> stack){
    Stack<String> container = new Stack<String>();
    while(!stack.empty() && (stack.peek() instanceof String)){
        container.push((String)stack.pop());
    }
    StringBuilder sb = new StringBuilder();
    while(!container.empty()){
        sb.append(container.pop());
    }
    return sb.toString();
 }
}